package com.specialtreasure.freightdepot.fragment;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.app.core.config.Constants;
import com.app.core.config.HttpApi;
import com.app.core.util.UserUtils;
import com.app.core.fragment.BaseNewFragment;
import com.chanven.lib.cptr.PtrClassicFrameLayout;
import com.chanven.lib.cptr.PtrDefaultHandler;
import com.chanven.lib.cptr.PtrFrameLayout;
import com.chanven.lib.cptr.loadmore.OnLoadMoreListener;
import com.specialtreasure.freightdepot.R;
import com.specialtreasure.freightdepot.adapter.MotorCadeAdapter;
import com.specialtreasure.freightdepot.model.Address;
import com.specialtreasure.freightdepot.model.BaseModel;
import com.specialtreasure.freightdepot.model.MotorCade;
import com.specialtreasure.freightdepot.model.MotorCadeBean;
import com.specialtreasure.freightdepot.model.MotorCadeData;
import com.specialtreasure.freightdepot.mq.MQMsg;
import com.specialtreasure.freightdepot.popupwindow.SelectCity;
import com.specialtreasure.freightdepot.popupwindow.SelectCityPW;
import com.specialtreasure.freightdepot.popupwindow.SelectTruckSingle;
import com.specialtreasure.freightdepot.popupwindow.SelectUnitPW;
import com.yanzhenjie.httpmodule.http.CallServer;
import com.yanzhenjie.httpmodule.http.Result;
import com.yanzhenjie.httpmodule.http.StringRequest;
import com.yanzhenjie.nohttp.Logger;
import com.yanzhenjie.nohttp.RequestMethod;
import com.yanzhenjie.nohttp.rest.CacheMode;
import com.yanzhenjie.nohttp.rest.Response;
import com.yanzhenjie.nohttp.rest.SimpleResponseListener;

import org.simple.eventbus.EventBus;
import org.simple.eventbus.Subscriber;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2017/8/7 0007.
 * 我的车队单页面  4个tab
 */

public class MeMotorCadeFragment extends BaseNewFragment implements View.OnClickListener {

    public static final String TAG = "MeMotorCadeFragment";
    String token;
    String carLength;//车长
    String carType;//车型
    Integer group;//（0.自有 1.外协）
    String runningRoute;//常跑路线(目的地)
    String runningRouteStart;//常跑路线(出发地)
    Integer count = 10;//每页条数
    Integer page = 1;//页数
    String province;//位置(省)
    String city;//位置(市


    List<MotorCadeBean> motorCadeDataList = new ArrayList<MotorCadeBean>();
    MotorCadeAdapter motorCadeAdapter;
    Boolean hasMode;

    private TextView tv_group;
    private RelativeLayout rl_group;
    private ListView lv_moto_cade;
    private PtrClassicFrameLayout ptr_layout;
    private LinearLayout ll_root;
    private TextView tv_chufadi;
    private RelativeLayout rl_chufadi;
    private TextView tv_mudidi;
    private RelativeLayout rl_mudidi;
    private TextView tv_car_length_type;
    private RelativeLayout rl_car_length_type;


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = View.inflate(mContext, R.layout.frag_moto_cade_four, null);
        initView(view);
        return view;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        // 注册对象
        EventBus.getDefault().register(this);
        setData();
    }

    private void setData() {

        //初始化自动刷新
        ptr_layout.postDelayed(new Runnable() {
            @Override
            public void run() {
                ptr_layout.autoRefresh(true);
            }
        }, 150);

        //下拉刷新
        ptr_layout.setPtrHandler(new PtrDefaultHandler() {
            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                ptr_layout.setLoadMoreEnable(true);
                page = 1;
                motorCadeDataList.clear();
                getData();
            }
        });

        //自动加载更多
        ptr_layout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void loadMore() {
                if (!hasMode) {
                    page++;
                    getData();
                } else {
                    Toast.makeText(mContext, "没有更多数据了", Toast.LENGTH_SHORT).show();
                    ptr_layout.setLoadMoreEnable(false);
                }
            }
        });

    }


    /**
     * 网络请求
     */
    private void getData() {
        token = UserUtils.getToken();
        String url = Constants.HTTP_URL + HttpApi.MYCARLIST;
        StringRequest request = new StringRequest(url, RequestMethod.POST);
        request.add("token", token);
        request.add("count", count);
        request.add("page", page);

        request.addNull("carLength", carLength);
        request.addNull("carType", carType);
        request.addNull("group", group);
        request.addNull("runningRoute", runningRoute);
        request.addNull("province", province);
        request.addNull("city", city);

        request.setCacheMode(CacheMode.ONLY_REQUEST_NETWORK);

        CallServer.getInstance().request(Constants.ZERO, request, new SimpleResponseListener<Result<String>>() {
            @Override
            public void onSucceed(int what, Response<Result<String>> response) {
                super.onSucceed(what, response);
                ptr_layout.refreshComplete();
                ptr_layout.loadMoreComplete(true);

                String result = response.get().getResult();
                Logger.e("请求成功：" + result);
                MotorCade motorCade = JSON.parseObject(result, MotorCade.class);

                if (motorCade != null) {
                    Integer status = motorCade.getStatus();
                    String msg = motorCade.getMsg();
                    //判断状态是
                    if (status != null && status == 0) {
                        MotorCadeData motorCadeData = motorCade.getData();
                        if (motorCadeData != null) {
                            hasMode = motorCadeData.getHasMore();
                            //适配数据
                            List<MotorCadeBean> motorCadetList = motorCadeData.getResultList();
                            if (motorCadetList != null && motorCadetList.size() > 0) {
                                ptr_layout.setLoadMoreEnable(true);
                                motorCadeDataList.addAll(motorCadetList);
                            } else {
                                ptr_layout.setLoadMoreEnable(false);
                            }

                            if (motorCadeAdapter == null) {
                                motorCadeAdapter = new MotorCadeAdapter(getActivity());
                                motorCadeAdapter.setMotorCadeDataList(motorCadeDataList);
                                lv_moto_cade.setAdapter(motorCadeAdapter);
                            } else {
                                motorCadeAdapter.setMotorCadeDataList(motorCadeDataList);
                                motorCadeAdapter.notifyDataSetChanged();
                            }

                        }

                    } else {
                        Toast.makeText(mContext, msg, Toast.LENGTH_SHORT).show();
                    }
                }

            }
        });
    }


    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.rl_group://分组
                SelectUnitPW supw8 = new SelectUnitPW(getActivity(), "fenzu.xml", "分组");
                supw8.showAtBottom(ll_root);
                supw8.setOnResultListener(new SelectUnitPW.OnResultListener() {
                    @Override
                    public void onResult(String str) {
                        if (!TextUtils.isEmpty(str)) {
                            tv_group.setText(str);
                            if (str.equals("不限")) {
                                group = null;
                            } else if (str.equals("自有")) {
                                group = 0;
                            } else {
                                group = 1;
                            }
                            ptr_layout.postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    ptr_layout.autoRefresh(true);
                                }
                            }, 150);

                        }
                    }
                });
                break;
            case R.id.rl_chufadi://长跑城市
                SelectCityPW pwTo = new SelectCityPW(getActivity());
                pwTo.showAtBottom(ll_root);
                pwTo.setOnResultListener(new SelectCityPW.OnResultListener() {
                    @Override
                    public void onResult(Address address) {
                        if (address != null) {
                            tv_chufadi.setText(address.province + address.city + address.region);
                            runningRoute = address.city;
                            //城市判断
                            if (address.province.equals(address.city)) {
                                tv_chufadi.setText(address.city + address.region);
                            }

                            ptr_layout.postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    ptr_layout.autoRefresh(true);
                                }
                            }, 150);

                        }
                    }

                });
                break;
            case R.id.rl_mudidi://位置 省和市
                SelectCity pwTo2 = new SelectCity(getActivity());
                pwTo2.showAtBottom(ll_root);
                pwTo2.setOnResultListener(new SelectCity.OnResultListener() {
                    @Override
                    public void onResult(Address address) {
                        if (address != null) {
                            province = address.province;
                            city = address.city;
                            tv_mudidi.setText(address.province + address.city);

                            //城市判断
                            if (address.province.equals(address.city)) {
                                province = "";
                                tv_mudidi.setText(address.city);
                            }

                            ptr_layout.postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    ptr_layout.autoRefresh(true);
                                }
                            }, 150);

                        }
                    }
                });
                break;
            case R.id.rl_car_length_type://车型车长
                SelectTruckSingle pwTo3 = new SelectTruckSingle(getActivity());
                pwTo3.showAtBottom(ll_root);
                pwTo3.setOnResultListener(new SelectTruckSingle.OnResultListener() {
                    @Override
                    public void onResult(String str) {
                        tv_car_length_type.setText(str);
                        ptr_layout.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                ptr_layout.autoRefresh(true);
                            }
                        }, 150);
                    }

                    @Override
                    public void onResult1(String str) {
                        carLength = str;
                    }

                    @Override
                    public void onResult2(String str) {
                        carType = str;
                    }
                });


        }

    }


    private void initView(View view) {

        tv_group = (TextView) view.findViewById(R.id.tv_group);
        rl_group = (RelativeLayout) view.findViewById(R.id.rl_group);
        rl_group.setOnClickListener(this);
        lv_moto_cade = (ListView) view.findViewById(R.id.lv_moto_cade);
        ptr_layout = (PtrClassicFrameLayout) view.findViewById(R.id.ptr_layout);
        ll_root = (LinearLayout) view.findViewById(R.id.ll_root);

        tv_chufadi = (TextView) view.findViewById(R.id.tv_chufadi);
        rl_chufadi = (RelativeLayout) view.findViewById(R.id.rl_chufadi);
        rl_chufadi.setOnClickListener(this);
        tv_mudidi = (TextView) view.findViewById(R.id.tv_mudidi);
        rl_mudidi = (RelativeLayout) view.findViewById(R.id.rl_mudidi);
        rl_mudidi.setOnClickListener(this);
        tv_car_length_type = (TextView) view.findViewById(R.id.tv_car_length_type);
        rl_car_length_type = (RelativeLayout) view.findViewById(R.id.rl_car_length_type);
        rl_car_length_type.setOnClickListener(this);
    }

    private void resetParameters() {
        carType = null;
        carLength = null;
        group = null;
        runningRouteStart = null;
        runningRoute = null;

        tv_group.setText("分组");
        tv_car_length_type.setText("车长车型");
        tv_chufadi.setText("出发地");
        tv_mudidi.setText("到达地");

    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        // 注销
        EventBus.getDefault().unregister(this);
    }

    @Override
    protected String getFragmentName() {
        return TAG;
    }

    @Subscriber(tag = Constants.UPDATEMETO)
    private void updateData(BaseModel baseModel) {
        ptr_layout.postDelayed(new Runnable() {
            @Override
            public void run() {
                ptr_layout.autoRefresh(true);
            }
        }, 150);

    }

    @Subscriber(tag = Constants.EventTag.ON_UPDATE_EMPTY)
    private void onUpdateEmpty(MQMsg mqMsg) {
        String json = mqMsg.msg;
        MotorCadeBean bean = JSON.parseObject(json, MotorCadeBean.class);
        for (int i = 0; i < motorCadeDataList.size(); i++) {
            if (motorCadeDataList.get(i).getcUserResp().getCuserId().equals(bean.getcUserResp().getCuserId())) {
                motorCadeDataList.set(i, bean);
                motorCadeAdapter.notifyDataSetChanged();
                break;
            }
        }
    }
}
